package com.poisonh.unifiedauth.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.adapter.FriendsAdapter;
import com.poisonh.unifiedauth.model.BusinessCard;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 名片夹
 */
public class FriendsActivity extends BaseActivity implements View.OnClickListener {
    private ListView listview_mpj;

    ArrayList<BusinessCard> data = new ArrayList<BusinessCard>();

    private FriendsAdapter friendsAdapter;
    // 要申请的权限
    private String[] permissions = {Manifest.permission.CALL_PHONE};
    private AlertDialog dialog;
    @Override
    protected void loadContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_friends);
        initTitleView();
        initView();
        SVProgressHUD.showWithStatus(this, "加载中...");
        QueryCardInfo();
    }

    @Override
    protected void initView() {
        mRightBtn.setVisibility(View.GONE);//右边三横的图片
        setTitleTxt("名片夹");


        listview_mpj = (ListView) findViewById(R.id.listview_mp);
        friendsAdapter = new FriendsAdapter(data, this);

        listview_mpj.setAdapter(friendsAdapter);

        //friendsAdapter.notifyDataSetChanged();
        mLeftBtn.setOnClickListener(this);

        //listview的点击事件
        listview_mpj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(FriendsActivity.this, CardetailsActivity.class);
                intent.putExtra("BusinessCard",data.get(i));

                intent.putExtra("list_location",i);
                //第二个参数为请求码，可以根据业务需求自己编号

                startActivityForResult(intent,0);

            }
        });

        //长按删除listview条目
//        listview_mpj.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//
//                //delete_B_uid=data.get(position).getUid();
//
//
//                //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
//                AlertDialog.Builder builder = new AlertDialog.Builder(FriendsActivity.this);
//                builder.setMessage("确定删除?");
//                builder.setTitle("提示");
////                BusinessCard mBusinessCard = data.get(position);//这个是要取出里面的东西来 和后台确认接口
////                delete_B_uid=mBusinessCard.getUid();
////                deleteCardInfo();//删除名片夹的方法
//                //添加AlertDialog.Builder对象的setPositiveButton()方法
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                       BusinessCard mBusinessCard = data.get(position);//这个是要取出里面的东西来 和后台确认接口
//                        String  delete_B_uid=mBusinessCard.getUid();
//                        //请求网络删除
//                       // deleteCardInfo(position,delete_B_uid);//删除名片夹的方法
//
////                        if (data.remove(position) != null) {
////                            System.out.println("success");
////                        } else {
////                            System.out.println("failed");
//////                        }
////                        friendsAdapter.notifyDataSetChanged();
////                        Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//                //添加AlertDialog.Builder对象的setNegativeButton()方法
//                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
//
//                builder.create().show();
//
//                return false;
//            }
//        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_left_btn:
                finish();
                break;
        }
    }


    /**
     * 获取用户名片信息
     */
    public void QueryCardInfo() {


        HttpParams params = new HttpParams();
        params.put("token", mStrUserToken);
        //扫描用户id
        params.put("userId", mStrUserId);
        //被扫描用户id
         // params.put("destId", bUerId);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.CARDUSERLIST, params, new MyHttpsUtils.ResultCallback() {
            @Override
            public void onSuccess(String response) {
                Log.e("Resonpse_mp_getcount", "onSuccess: "+response.toString());
                try {
                    JSONObject object = new JSONObject(response);
                    String code = object.getString("code");
                    if ("200".equals(code)) {
                        String results=object.getString("results");
                        Gson gson = new Gson();
                        ArrayList<BusinessCard> list=gson.fromJson(results,new TypeToken<ArrayList<BusinessCard>>(){}.getType());

                        data.addAll(list);
                        friendsAdapter.notifyDataSetChanged();
                        SVProgressHUD.dismiss(FriendsActivity.this);
//                        Toast.makeText(FriendsActivity.this,"加载成功",Toast.LENGTH_SHORT).show();
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(FriendsActivity.this,"加载失败",Toast.LENGTH_SHORT).show();
                }
                Log.d("AAA", response);

            }

            @Override
            public void onFailure(String failReason)

            {
                Log.d("AAA", failReason);
                SVProgressHUD.dismiss(FriendsActivity.this);
                Toast.makeText(FriendsActivity.this,"加载失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    //第一个参数为请求码，即调用startActivityForResult()传递过去的值
    //第二个参数为结果码，结果码用于标识返回数据来自哪个新Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datat) {
        switch(resultCode){
            case 0:
                    if(datat!=null){
                        int delete_location=datat.getIntExtra("delete_location",-1);
                        if (delete_location > -1 && delete_location < data.size())
                            data.remove(delete_location);
                        friendsAdapter.notifyDataSetChanged();
                }


            case 2:
                // NewActivity的返回数据
        }

        super.onActivityResult(requestCode, resultCode, datat);
    }

}
